<script setup>
import { ref ,watch,onMounted} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryPageApi,addApi,queryInfoApi,updateApi,deleteApi} from '../../api/clazz'
import { queryPageApi as getEmpList} from '../../api/emp'

// 定义搜索表单的初始值
const searchClazz = ref({name:'',date:[], beginDate:'',endDate:''})

//定义响应数据
const emps = ref([])

//钩子函数
onMounted(() => {
  search();
})

onMounted(async () => {
  const result = await getEmpList('', '', '', '', 1, 100) // 空参数表示不筛选
  if (result.code) {
    emps.value = result.data.rows
  } else {
    ElMessage.error('加载员工失败')
  }
})

//侦听searchClazz的date属性
watch(() => searchClazz.value.date, (newVal,oldVal) => {
  if(newVal.length == 2){
    searchClazz.value.beginDate = newVal[0];
    searchClazz.value.endDate = newVal[1];
  }else{
    searchClazz.value.beginDate = '';
    searchClazz.value.endDate = '';
  }
})

//学科列表数据
const subjects = ref([
    {name:'Java',value:1},
    {name:'前端',value:2},
    {name:'大数据',value:3},
    {name:'Python',value:4},
    {name:'Go',value:5},
    {name:'嵌入式',value:6}
])


//班级列表数据
const clazzList = ref([])

//  查询班级列表
const search = async () => {
  const result = await queryPageApi(
    searchClazz.value.name,
    searchClazz.value.beginDate,
    searchClazz.value.endDate,
    currentPage.value,
    pageSize.value
  );
  if(result.code){
    clazzList.value = result.data.rows;
    total.value = result.data.total;
  }
}

// 清空查询条件
const clear = () => {
 searchClazz.value = {name:'',date:[], begin:'',end:''} 
 search();
}

// 新增/编辑班级表单
const clazz = ref({
  "name":'',
  "room":'',
  "beginDate":'',
  "endDate":'',
  "masterId":'',
  "subject":'' 
})

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('新增班级')

// 新增班级
const addClazz = () => {
  dialogTitle.value = '新增班级'
  dialogVisible.value = true;
  clazz.value = {
    "name":'',
    "room":'',
    "beginDate":'',
    "endDate":'',
    "masterId":'',
    "subject":'' 
  }
  //重置表单的校验规则提示信息
  if(clazzFormRef.value){
    clazzFormRef.value.resetFields();
  }
}

//保存班级
const save = async () => {
   console.log(clazz.value);
   //表单校验
   if(!clazzFormRef.value) return;
   clazzFormRef.value.validate(async (valid) => {
      if(valid){
        let result;
        if(clazz.value.id){
          //修改
          result = await updateApi(clazz.value);
        }else{
          //新增
          result = await addApi(clazz.value);
        }
        if(result.code){
          ElMessage.success('保存成功')
          search();
          dialogVisible.value = false;
        }else{//失败
          ElMessage.error(result.msg);
        }
      }else{//失败
        ElMessage.error('请填写正确信息');
      } 
   })
}

//表单引用
const clazzFormRef = ref();

//表单校验规则
const rules = ref({
 name:[
  {required:true,message:'请输入班级名称',trigger:'blur'},
  {min:4,max:30,message:'长度在4到30个字符',trigger:'blur'}
 ],
 beginDate:[
  {required:true,message:'请选择开始时间',trigger:'change'},
 ],
 endDate:[
  {required:true,message:'请选择结束时间',trigger:'change'},  
 ],
 subject:[
  {required:true,message:'请选择学科',trigger:'change'},
 ]
});

//修改班级
const edit = async (id) => {
  const result = await queryInfoApi(id);
  if(result.code){
    dialogTitle.value = '修改班级'
    dialogVisible.value = true;
    clazz.value = result.data; 
  }
}

//删除班级
const deleteById = async (id) =>{
  //消息弹出框
  ElMessageBox.confirm(
    '您确认删除该班级吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => { //点击确认按钮
    const result = await deleteApi(id);
    if(result.code){
      ElMessage.success('删除成功');
      search();
    }else{
      ElMessage.error(result.msg);
    }
  }).catch(() => { //点击取消按钮
    ElMessage.success('已取消删除');
  })
}


// 分页相关的数据模型
const currentPage = ref(1)  // 当前页码
const pageSize = ref(10)  // 每页显示条数
const background = ref(false) // 是否显示分页
const total = ref(0)  // 总记录数
//  分页大小改变的回调
const handleSizeChange = (val) => {
  console.log(`每页展示${val}条记录`)
  search();
}
//  当前页改变的回调
const handleCurrentChange = (val) => {
  console.log(`当前页码: ${val}`)
  search();
}

</script>

<template>
  <h1>班级管理</h1>
  <!-- 搜索表单 -->
  <div class="container">
      <el-form :inline="true" :model="searchClazz" class="demo-form-inline">
        <el-form-item label="班级名称">
          <el-input v-model="searchClazz.name" placeholder="请输入班级名称" clearable />
        </el-form-item>

      <el-form-item label="结课时间">
        <el-date-picker
          v-model="searchClazz.date"
          type="daterange"
          unlink-panels
          range-separator="到"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :size="size"
          value-format="YYYY-MM-DD"
          /></el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="info" @click="clear">清空</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 功能按钮 -->
  <div class="container">
    <el-button type="primary" @click="addClazz">+ 新增班级</el-button>
  </div>

  <!-- 表格 -->
  <div class="container">
    <el-table :data="clazzList" border style="width: 100%">
    <el-table-column type="index" label="序号" width="60" align="center"/>
    <el-table-column prop="name" label="班级名称" width="170" align="center"/>
    <el-table-column prop="room" label="班级教室" width="120" align="center"/>
    <el-table-column label="班主任" width="120" align="center">
      <template #default="scope">
        {{ scope.row.masterName || '暂无班主任' }}
      </template>
    </el-table-column>
    <el-table-column prop="beginDate" label="开课时间" width="150" align="center"/>
    <el-table-column prop="endDate" label="结课时间" width="150" align="center"/>
    <el-table-column prop="status" label="状态" width="120" align="center"/>
    <el-table-column prop="updateTime" label="最后操作时间" width="180" align="center"/>
    <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="edit(scope.row.id)"><el-icon><EditPen /></el-icon>编辑</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row.id)"><el-icon><DeleteFilled /></el-icon>删除</el-button>
          </template>
        </el-table-column>
    </el-table>
  </div>

  <!-- 分页条 -->
  <div class="container">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10,20,30,50,75,100]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增班级窗口/修改班级窗口 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="clazz" :rules="rules" ref="clazzFormRef" label-width="80px">
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="班级名称" prop="name">
              <el-input v-model="clazz.name" placeholder="请输入班级名称，如西安黑马JavaEE就业100期"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="班级教室" prop="room">
              <el-input v-model="clazz.room" placeholder="请输入班级教室"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="开课时间">
              <el-date-picker
                v-model="clazz.beginDate"
                type="date"
                placeholder="请选择开课时间"
                :size="size"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="结课时间">
              <el-date-picker
                v-model="clazz.endDate"
                type="date"
                placeholder="请选择结课时间"
                :size="size"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="班主任">
              <el-select v-model="clazz.masterId" placeholder="请选择班主任" style="width: 100%;">
                <el-option
                  v-for="e in emps"
                  :key="e.id"
                  :label="e.name"
                  :value="e.id">
                </el-option>
            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        

      <!-- 第六行 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="学科">
              <el-select v-model="clazz.subject" placeholder="请选择学科" style="width: 100%;">
                <el-option v-for="s in subjects" :key="s.value" :label="s.name" :value="s.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
      
  </el-dialog>




</template>

<style scoped>
.container{
  margin: 10px 0px;
}
</style>